package com.sx.zongzhi.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.util.ArrayMap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.DealWayAdapter;
import com.sx.zongzhi.adapter.DisputePendingAdapter;
import com.sx.zongzhi.adapter.TextSelectAdapter;
import com.sx.zongzhi.bean.DisputeBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.OrganizingBean;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.presenter.DisputePest;
import com.sx.zongzhi.utils.AppConstants;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IDisputeView;
import com.sx.zongzhi.widget.CustomDialog;
import com.sx.zongzhi.widget.LoadDialog;
import com.sx.zongzhi.widget.MyPopupWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**
 * 矛盾纠纷
 */
public class DisputePendingActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener
        ,IDisputeView{

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.imvAdd)
    ImageView imvAdd;
    private DisputePendingAdapter pendingAdapter;
    private List<DisputeBean.RowsBean> disputeBeanList=new ArrayList<>();
    private List<String> titleTy=new ArrayList<>();
    private MyPopupWindow typePopupWindow,dealPopupWindow;
    private TextSelectAdapter selectAdapter;
    private DisputePest presenter;
    /**矛盾纠纷地址类型*/
    private final ArrayMap<String,String> urlState=new ArrayMap<>();
    /**筛选条件*/
    private int currentPage=1;
    private String eventName="";
    private String orgId="";
    private String issueKind="";
    private String eventSource="";
    private String startTime="";
    private String endTime="";
    private String eventType="";
    /**
     * 当前列表 0：待办 1：已办 2：办结 3：下辖待办 4：下辖已办 5：历史遗留
     */
    private String DEAL_TYPE;
    private Disposable disposable;
        /**当前的选择的*/
    private DisputeBean.RowsBean rowsBean;
    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.refresh_recyclerview);
        ButterKnife.bind(this);
        DEAL_TYPE=getIntent().getStringExtra("DEAL_TYPE");
        setTitleName(DEAL_TYPE,R.mipmap.icon_drop_down);
        setRightImage(R.mipmap.icon_nav_search);
        setRightImage2(R.mipmap.icon_nav_position);
        setRightImage2Hide();
        presenter=new DisputePest(this);
        initView();
        initData();
        onRefresh();
    }

    //初始化数据
    private void initData() {
        urlState.put("矛盾纠纷-待办","findAppMyNeedDo.action");//待办
        urlState.put("矛盾纠纷-已办","findAppMyDone.action");//已办
        urlState.put("矛盾纠纷-办结","findAppMyCompleted.action");//办结
        urlState.put("矛盾纠纷下辖-待办","findAppJurisdictionsNeedDo.action");//下辖待办
        urlState.put("矛盾纠纷下辖-办结","findAppJurisdictionsCompleted.action");//下辖办结
        urlState.put("历史遗留","findAppMyHistoricIssues.action");//历史遗留
        //订阅筛选组织机构
        disposable= MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent bean) throws Exception {
                        if ("DisputePendingActivity".equals(bean.getRequest())) {
                            if (bean.getType()==0) {
                                OrganizingBean oBean = (OrganizingBean) bean.getMsg();
                                if (oBean != null) {
                                    currentPage=1;
                                    orgId = oBean.getId();
                                    getDataList();
                                }
                            }else {
                                onRefresh();
                            }
                        }
                    }
                });

    }

    private void initView() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(AppConstants.colors);
            swipeRefreshLayout.setOnRefreshListener(this);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        pendingAdapter = new DisputePendingAdapter(this,R.layout.item_dispute_pending_list,disputeBeanList);
        pendingAdapter.setEmptyView(View.inflate(this,R.layout.load_error_view,null));
        recyclerView.setAdapter(pendingAdapter);
        pendingAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                currentPage++;
                getDataList();
            }
        },recyclerView);
        pendingAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent=new Intent(DisputePendingActivity.this, DisputeDetailActivity.class);
                intent.putExtra("DisputeBean.RowsBean",disputeBeanList.get(position));
                startActivity(intent);
            }
        });
    }

    @OnClick({R.id.tv_title,R.id.imv_Right,R.id.imvAdd,R.id.imv_Right2})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.tv_title:
                createTypePop();
                break;
            case R.id.imv_Right:
                startActivityForResult(new Intent(DisputePendingActivity.this,DisputeSearchActivity.class)
                        ,4441);
                break;
            case R.id.imv_Right2://位置筛选
                startActivity(new Intent(this,OrganizingActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT,"DisputePendingActivity"));
                break;
            case R.id.imvAdd:
                startActivity(new Intent(DisputePendingActivity.this,DisputeAddActivity.class)
                        .putExtra(Global.ACTIVITY_FRAGMENT,"DisputePendingActivity"));
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 4441://查询返回
                    currentPage=1;
                    eventName = intent.getStringExtra("EventName");
                    issueKind = intent.getStringExtra("EventScale");
                    eventSource = intent.getStringExtra("EventSource");
                    startTime = intent.getStringExtra("StartTime");
                    endTime = intent.getStringExtra("EndTime");
                    eventType = intent.getStringExtra("EventType");
                    getDataList();
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (disposable!=null){
            disposable.dispose();
        }
        super.onDestroy();
    }

    /**
     * 创建显示事件类型的弹窗
     */
    private void createTypePop() {
        if (typePopupWindow == null) {
            titleTy.add("矛盾纠纷-待办");
            titleTy.add("矛盾纠纷-已办");
            titleTy.add("矛盾纠纷-办结");
            IDataStorage dataStorage= DataStorageFactory.getInstance(
                    getApplicationContext(),
                    DataStorageFactory.TYPE_DATABASE);
            UserBean userBean = dataStorage.load(UserBean.class,getPackageName());
            orgId = userBean.getOrg().getId();
            imvAdd.setVisibility(View.GONE);
            if (!"片组片格".equals(userBean.getOrg().getOrgLevel().getDisplayName())){
                titleTy.add("矛盾纠纷下辖-待办");
                titleTy.add("矛盾纠纷下辖-办结");
            }
            titleTy.add("历史遗留");
            View view = LayoutInflater.from(this).inflate(R.layout.pop_select_type, null);
            typePopupWindow = new MyPopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            typePopupWindow.setTouchable(true);
            typePopupWindow.setOutsideTouchable(false);
            typePopupWindow.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
            selectAdapter=new TextSelectAdapter(this,R.layout.item_pop_text_select,titleTy);
            if(DEAL_TYPE.equals("矛盾纠纷-已办")){
                selectAdapter.setItemSelect(1);
            }else if(DEAL_TYPE.equals("矛盾纠纷-办结")){
                selectAdapter.setItemSelect(2);
            }else {
                selectAdapter.setItemSelect(0);
            }
            ListView listview = (ListView) view.findViewById(R.id.list_View);
            listview.setAdapter(selectAdapter);
            listview.setOnItemClickListener(typeItemClick);
            view.findViewById(R.id.fl_Prent).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    typePopupWindow.dismiss();
                }
            });
        }

        typePopupWindow.showAsDropDown(findViewById(R.id.toolbar));
    }

    /**
     * 创建更多事件处理的弹窗
     */
    public void createDealPop(List<String> permissionList) {

        View view = LayoutInflater.from(this).inflate(R.layout.pop_select_type, null);
        ListView listview = (ListView) view.findViewById(R.id.list_View);
        if (dealPopupWindow == null) {
            dealPopupWindow = new MyPopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            dealPopupWindow.setTouchable(true);
            dealPopupWindow.setOutsideTouchable(true);
            dealPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));

        }
        DealWayAdapter dealWayAdapter=new DealWayAdapter(this,R.layout.item_text,permissionList);
        listview.setAdapter(dealWayAdapter);
        listview.setOnItemClickListener(new MyOnItemClickListener());
        view.findViewById(R.id.fl_Prent).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dealPopupWindow.dismiss();
            }
        });
    }
    /**
     * 显示
     */
    public void showDealPop(DisputeBean.RowsBean rowsBean) {
        this.rowsBean=rowsBean;
        if (dealPopupWindow!=null){
            dealPopupWindow.showAsDropDown(findViewById(R.id.toolbar));
        }
    }

    AdapterView.OnItemClickListener typeItemClick=new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String title=titleTy.get(position);
            setTitleName(titleTy.get(position));
            if (title.equals("矛盾纠纷-待办")||title.equals("矛盾纠纷-已办")||title.equals("矛盾纠纷-办结")){
                setRightImage2Hide();
            }
            if (title.equals("矛盾纠纷下辖-待办")||title.equals("矛盾纠纷下辖-办结")||title.equals("历史遗留")){
                setRightImage2Show();
            }
            selectAdapter.setItemSelect(position);
            typePopupWindow.dismiss();
            DEAL_TYPE= titleTy.get(position);
            onRefresh();
        }
    };

    private class MyOnItemClickListener implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String dealType= parent.getAdapter().getItem(position).toString();

            if (dealType.equals("修改")){
                startActivity(new Intent(DisputePendingActivity.this,DisputeEditActivity.class)
                        .putExtra("DisputeBean.RowsBean",rowsBean));
            }
            if (dealType.equals("删除")||dealType.equals("历史遗留")){
                createDelete(dealType);
            }
            if (dealType.equals("加急")||dealType.equals("领导批示")||dealType.equals("普通督办")
                    ||dealType.equals("黄牌督办") ||dealType.equals("红牌督办")){
                createEdit(dealType);
            }

            dealPopupWindow.dismiss();
        }
    }

    /**
     * 带输入框的dialog
     */
    private void createEdit(final String title) {
        View view=LayoutInflater.from(this).inflate(R.layout.dialog_edittext,null);
        TextView tvTitle= (TextView) view.findViewById(R.id.dialog_title);
        tvTitle.setText(title);
        final EditText etContent= (EditText) view.findViewById(R.id.dialog_message);
        Button btCancel=(Button) view.findViewById(R.id.dialog_back);
        Button btOk=(Button) view.findViewById(R.id.dialog_confirm);
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.setView(view).setCancelable(false).create();
        dialog.show();
        btCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content=etContent.getText().toString();
                if (BaseUtil.isEmpty(content)){
                    ToastUtils.showToast(DisputePendingActivity.this,"请输入您的意见");
                    return;
                }
                if ("加急".equals(title)){
                    presenter.disputeMoreDeal("dealIssueUrgent.action",rowsBean.getIssueStepId(),content);
                }
                if ("领导批示".equals(title)){
                    presenter.disputeMoreDeal("dealIssueInstruct.action",rowsBean.getIssueStepId(),content);
                }
                if ("普通督办".equals(title)){
                    presenter.disputeMoreDeal("dealIssueSupervise.action","",rowsBean.getIssueStepId()
                            ,content,81);
                }
                if ("黄牌督办".equals(title)){
                    presenter.disputeMoreDeal("dealIssueSupervise.action","",rowsBean.getIssueStepId()
                            ,content,83);
                }
                if ("红牌督办".equals(title)){
                    presenter.disputeMoreDeal("dealIssueSupervise.action","",rowsBean.getIssueStepId()
                            ,content,86);
                }
                dialog.dismiss();
            }
        });
    }

    /**
     * 删除/历史遗留
     */
    private void createDelete(final String type) {
        String title;
        if ("删除".equals(type)){
            title="确定删除此事件吗？";
        }else {
            title="确定历史遗留？";
        }
        CustomDialog.Builder builder=new CustomDialog.Builder(this);
        CustomDialog dialog=builder.setMessage(title).
                setBackButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setConfirmButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if ("删除".equals(type)) {
                    presenter.disputeMoreDeal("deleteIssueById.action", rowsBean.getId());
                }else {
                    presenter.disputeMoreDeal("dealIssueHistoric.action",rowsBean.getIssueStepId(),"");
                }
                dialog.dismiss();
            }
        }).create();
        dialog.show();
    }


    @Override
    public void onRefresh() {
        currentPage=1;
        eventName="";
        issueKind="";
        eventSource="";
        startTime="";
        endTime="";
        eventType="";
        getDataList();
    }
    public void getDataList() {
        presenter.getDisputeList(urlState.get(DEAL_TYPE),orgId,eventName,issueKind,eventSource,
                startTime,endTime,eventType,currentPage,6);
    }

    /**
     * 获取矛盾纠纷
     * @param disputeBean
     */
    @Override
    public void getDisputeList(DisputeBean disputeBean) {
        swipeRefreshLayout.setRefreshing(false);
        imvAdd.setVisibility(View.GONE);
        if (disputeBean.getPermission()!=null){
            if(DEAL_TYPE.equals("矛盾纠纷-待办")){
              if (disputeBean.getPermission().isAddIssue()){
                  imvAdd.setVisibility(View.VISIBLE);
              }
                createDealPop(disputeBean.getPermissionList());
            }
            if(DEAL_TYPE.equals("矛盾纠纷下辖-待办")){
                createDealPop(disputeBean.getIssuePermissionList());
            }

        }
        if (currentPage==1){
            disputeBeanList.clear();
            pendingAdapter.setNewData(disputeBeanList);
        }
        if (disputeBean.getRows()!=null&&disputeBean.getRows().size()>0) {
            disputeBeanList.addAll(disputeBean.getRows());
        }
        if (disputeBeanList.size()>=disputeBean.getRecords()){
            pendingAdapter.loadMoreEnd();
        }else {
            pendingAdapter.loadMoreComplete();
        }
        pendingAdapter.notifyDataSetChanged();
    }

    /**
     * 事件受理
     * @param issueStepId 事件步骤主键
     */
    public void acceptDispute(String issueStepId){
        presenter.disputeAccept(issueStepId);
    }

    @Override
    public void showError(String message) {
        if (swipeRefreshLayout.isRefreshing()){
            swipeRefreshLayout.setRefreshing(false);
        }
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this,message);
    }

    /**
     * 受理成功提示
     * @param message
     */
    @Override
    public void accept(String message) {
        LoadDialog.dismiss(this);
        onRefresh();
        ToastUtils.showToast(this,message);
    }
}
